package snaptest.tool.ui;

import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import snaptest.bitbucket.EqUtil;
import snaptest.repo.FileRepo;
import snaptest.repo.RepoManager;

public class FileListingModel {

	private final DefaultListModel listModel = new DefaultListModel();

	private final DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();

	private Integer selectionIndex;

	private FileDiffModel fileDiffModel = new FileDiffModel();

	public FileListingModel() {
		selectionModel.addListSelectionListener(new SelectionListener());
	}

	public FileDiffModel getFileDiffModel() {
		return fileDiffModel;
	}

	public void setFileDiffModel(FileDiffModel fileDiffModel) {
		this.fileDiffModel = fileDiffModel;
	}

	private class SelectionListener implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent e) {
			Integer newSelectionIndex = getSelectionIndex();
			if (!EqUtil.eq(selectionIndex, newSelectionIndex)) {
				setSelectedEntry(newSelectionIndex);
			}
		}

	}

	private void setSelectedEntry(Integer newSelectionIndex) {
		this.selectionIndex = newSelectionIndex;
		System.out.println(getSelectedEntry());
		if (fileDiffModel != null) {
			fileDiffModel.setSelectedFile(getSelectedEntry());
		}
	}

	private String getSelectedEntry() {
		return selectionIndex == null ? null : (String) listModel.getElementAt(selectionIndex);
	}

	private Integer getSelectionIndex() {
		int first = selectionModel.getMinSelectionIndex();
		return first < 0 ? null : first;
	}

	public ListModel getListModel() {
		return listModel;
	}

	public ListSelectionModel getSelectionModel() {
		return selectionModel;
	}

	public void loadListing() {
		FileRepo tmpRepo = RepoManager.getTemporaryRepo();
		for (String entry : tmpRepo.scan()) {
			listModel.addElement(entry);
		}
	}

}
